//
//  AbbNavigationController.swift
//  AbbNavigationController
//
//  Created by abb on 16/7/31.
//  Copyright © 2016年 abb. All rights reserved.
//

import UIKit

class AbbNavigationController:UINavigationController {
    /// 是否添加假NavigationBar
    var shouldAddFakeNavigationBar:Bool?
    /**
     初始化方法
     因为要在初始化的时候,注册自定义的NavigationBar,所以需要手动push根控制器
     */
    override init(rootViewController:UIViewController) {
        super.init(navigationBarClass: AbbNavigationBar.self, toolbarClass: UIToolbar.self)
        self.pushViewController(rootViewController, animated: false)
    }
    /**
     如果继承UIViewController,您必须调用超实现这一点方法,即使你没有使用nib,否则会下列错误
     fatal error: use of unimplemented initializer 'init(nibName:bundle:)' for class 'AbbNavigationController.AbbNavigationController'
     由于我们使用了super.init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?)
     所以必须在这里调用一次super.init(nibName: nil, bundle: nil)
     */
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nil, bundle: nil)
    }
    /**
     获取当前控制器和即将push的控制器
     如果两者的"透明"方案不一致,则提醒添加假NavigationBar,反之亦然
     因为从一个navBar不透明的控制器,push到一个navBar透明的控制器时
     在push的过程中,由于当前控制器与即将push的控制器共用一个navBar
     所以设置即将push的控制器的navBar为透明后,当前控制器的navBar也会变为透明
     所以需要设置一个假的navBar,使之与当前控制器的navBar相同,这样push的过程中
     就能实现当前控制器的navBar不改变不消失的假象.
     */
    override func pushViewController(viewController: UIViewController, animated: Bool) {
        
        let currentVC:AbbBaseViewController? = self.viewControllers.last as? AbbBaseViewController
        // push时隐藏tabBar
        if self.viewControllers.count > 0 {
            viewController.hidesBottomBarWhenPushed = true
        }
        if !(viewController as! AbbBaseViewController).userTransparentNavigationBar && (currentVC == nil ? true : !currentVC!.userTransparentNavigationBar) {
            self.shouldAddFakeNavigationBar = false
        } else {
            self.shouldAddFakeNavigationBar = true
        }
        super.pushViewController(viewController, animated: animated)
    }
    /**
     同上
     */
    override func popViewControllerAnimated(animated: Bool) -> UIViewController? {
        let previousVC:AbbBaseViewController = self.viewControllers[self.viewControllers.count - 2] as! AbbBaseViewController
        let currentVC:AbbBaseViewController = self.viewControllers.last as! AbbBaseViewController
        if !currentVC.userTransparentNavigationBar && !previousVC.userTransparentNavigationBar {
            self.shouldAddFakeNavigationBar = false
        } else {
            self.shouldAddFakeNavigationBar = true
        }
        return super.popViewControllerAnimated(animated)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
